<template>
  <el-card class="column-left" ref="elCardRefStore">
    <template #header>
      <div class="card-header">
        <span>浏览器</span>
        <svg-icon
          class-name="iconfont active"
          @click="emits('changeHide')"
          icon-class="error"
        />
      </div>
    </template>
    <el-row class="tool-header">
      <svg-icon
        v-for="(item, index) in leftTool"
        :title="item.label"
        class-name="iconfont"
        @click="handleTool(index)"
        :key="item.id"
        :icon-class="item.icon"
      />
    </el-row>
    <div class="server-list">
      <el-tree
        :data="data"
        highlight-current
        :props="defaultProps"
        class="postmap-tree-store"
        node-key="layerCode"
        default-expand-all
        backgroundColor="#000"
        @node-click="handleNodeClick"
        ref="treeol"
        @check-change="handleCheckChange"
        @node-contextmenu="handleContextMenu"
        style="height: 100%"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <div>
              <svg-icon
                class-name="iconfont treeicon"
                :icon-class="iconTRype[data.type] || iconTRype.default "
              />
              <span>{{ data.label }}</span>
            </div>
          </span>
        </template>
      </el-tree>
    </div>
  </el-card>
  <ContextMenu
    :menuItems="componentAMenuItems"
    v-model:visible="menuFlag"
    ref="contextMenuRef"
  />
</template>

<script setup>
import { nextTick, defineEmits } from "vue";
import ContextMenu from "../common/ContextMenu.vue";
import { listMapStore, listMapStoreTree } from "../../../api/postmap/mapstore";
import {iconTRype} from '../util/iconProfiles';
import { useXmapStore } from "../../../store/modules/xmap";
// 使用 Pinia Store
const xmapStore = useXmapStore();

const emits = defineEmits(["changeHide", "onNodeMenuItem"]);
const menuFlag = ref(false);
const contextMenuRef = ref(null);
// 记录选中的菜单项
const selectMenu = ref(null);
const selectNode = ref(null);

const dataInit = () => {
  var query = {};
  listMapStoreTree(query).then((res) => {
    data.value = res.rows;
  });
};

const componentAMenuItemsFun = (e) => {
  selectMenu.value = e;
  alert("点击了" + JSON.stringify(e));
};

/**
 *
 */
const nodeMenuItemClick = (e) => {
  // console.info(selectMenu,selectNode);
  var event = {
    node: selectNode,
    menu: selectMenu,
  };
  //
  xmapStore.add(selectNode);

  emits("onNodeMenuItem", event);
};

//右键列表菜单
const componentAMenuItems = [
  { label: "刷新", cb: nodeMenuItemClick, icon: "huanjingshezhi" },
  { label: "编辑连接", cb: nodeMenuItemClick, icon: "huanjingshezhi" },
  { label: "删除连接", cb: nodeMenuItemClick, icon: "huanjingshezhi" },
  { label: "导出图层", cb: nodeMenuItemClick, icon: "huanjingshezhi" },
  { label: "删除图层", cb: nodeMenuItemClick, icon: "huanjingshezhi" },
  { label: "添加到地图", cb: nodeMenuItemClick, icon: "huanjingshezhi" },
  { label: "图层属性", cb: nodeMenuItemClick, icon: "huanjingshezhi" },
];
//左侧工具栏状态
const leftToolStatus = ref(-1);
const leftTool = [
  {
    id: 1,
    icon: "peitujiancha",
    label: "刷新",
  },
  {
    id: 2,
    icon: "jisuanji",
    label: "过滤",
  },
];

const handleTool = (index) => {
  alert("点击了按钮");
  leftToolStatus.value = index;
};

//左侧树数据
const data = ref([]);

//判断类型为shp或者为table 加上特定类名不显示小箭头
const customNodeClass = (data, node) => {
  var type = data.type;
  if (type === "shp" || type === "table") {
    return "is-penultimate";
  }
  return "";
};
const defaultProps = {
  children: "children",
  label: "label",
  class:customNodeClass
};
//关闭表格
const closeTable = () => {
  emits("changeHide");
};

const handleContextMenu = (event, node) => {
  selectNode.value = node;
  // 阻止默认的右键菜单行为
  event.preventDefault();
  // 获取右键菜单组件实例并设置其显示位置为鼠标点击位置
  const context = contextMenuRef.value;
  menuFlag.value = true;
  let x = event.clientX;
  let y = event.clientY;
  // 创建右键事件对象
  var rightClickEvent = new MouseEvent("contextmenu", {
    bubbles: true,
    cancelable: true,
    view: window,
    button: 2,
    buttons: 2,
    clientX: 0,
    clientY: 0,
  });
  // 手动触发右键事件
  treeol.value.$el.dispatchEvent(rightClickEvent);
  // 获取页面可视区域的宽度和高度
  const pageWidth = document.documentElement.clientWidth;
  const pageHeight = document.documentElement.clientHeight;
  nextTick(() => {
    // 获取右键菜单自身的宽度和高度（这里假设右键菜单已经渲染完成，可以获取到准确的尺寸）
    const menuWidth = context.$el.offsetWidth;
    const menuHeight = context.$el.offsetHeight;
    // 判断右键菜单是否超出页面右侧边界，如果超出则将其左侧位置调整为边界内
    if (x + menuWidth > pageWidth) {
      x = pageWidth - menuWidth;
    }

    // 判断右键菜单是否超出页面底部边界，如果超出则将其顶部位置往上调整
    if (y + menuHeight > pageHeight) {
      y = Math.max(0, y - menuHeight);
    }

    context.$el.style.left = x + "px";
    context.$el.style.top = y + "px";
  });
};

const elCardRefStore = ref(null);
const treeol = ref(null);
const isDOM = (e) => {
  e.preventDefault();
  const target = e.target;
  var isUnderTopElement = elCardRefStore.value.$el.contains(target);
  if (!isUnderTopElement) {
    menuFlag.value = false;
  }
};
const wClick = (e) => {
  const target = e.target;
  const toolA = contextMenuRef.value.$el;
  const isInsideTool = toolA && toolA.contains(target);
  if (!isInsideTool) {
    menuFlag.value = false;
  }
};
onMounted(() => {
  window.addEventListener("click", wClick);
  // 监听整个窗口的右键点击事件
  window.addEventListener("contextmenu", isDOM);

  dataInit();
});
onUnmounted(() => {
  window.removeEventListener("click", wClick);
  window.removeEventListener("contextmenu", isDOM);
});
</script>

<style lang="scss">
.postmap-tree-store {
  /* 鼠标浮动过的背景颜色 */
  .el-tree-node__content:hover {
    background: #0074b7;
    color: #fff;
  }

  /* 鼠标点击时节点的背景颜色 */
  .el-tree-node:focus > .el-tree-node__content {
    background-color: #0074b7 !important;
    color: rgb(255, 255, 255);
  }

  /* 鼠标失去焦点时节点背景的颜色 */
  .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background: rgb(0, 129, 204) !important;
  }
  .el-tree-node__content > .el-tree-node__expand-icon {
    color: var(--el-tree-expand-icon-color) !important;
    visibility: inherit !important;
  }
  .is-penultimate {
    .el-tree-node__content > .el-tree-node__expand-icon {
      visibility: hidden !important;
    }
  }
}
</style><style lang="scss" scoped>
.active {
  color: #21a3f1;
}
.card-header {
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
  box-sizing: border-box;
  align-items: center;
  height: 100%;
}

.column-left {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tool-header {
  padding-bottom: 1px;
  border-bottom: 1px solid var(--el-card-border-color);
  padding: 3px 10px;
  box-sizing: border-box;
}
.server-list {
  height: calc(100% - 34px);
  flex: 1;
  overflow: auto;
  padding: 5px;
  box-sizing: border-box;
}
:deep(.el-card__header) {
  padding: 5px !important;
  max-height: 30px !important;
  min-height: 30px !important;
}
:deep(.el-card__body) {
  height: calc(100% - 40px);
  flex: 1;
  overflow: auto;
  padding: 0 !important;
}

.iconfont {
  width: 24px;
  height: 24px;
  font-size: 24px;
  cursor: pointer;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding-right: 5px;

  svg {
    margin-right: 10px;
  }

  div {
    display: flex;
    align-items: center;

    i {
      margin-right: 4px;
    }
  }

  .btn {
    color: rgb(50, 98, 230);
  }
}
</style>
